package com.heima.filter;

import cn.hutool.core.util.StrUtil;
import com.heima.config.MyConfig;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Resource
    private MyConfig myConfig;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取白名单
        String[] noAuthPaths = myConfig.getNoAuthPaths();
        ServerHttpResponse respons = exchange.getResponse();

        // 获取请求路径
        String path = exchange.getRequest().getURI().getPath();

        // 遍历npAuthPath，看看请求路径是否匹配白名单
        for (String s : noAuthPaths) {
            if (antPathMatcher.match(s, path)){
                // 放行
                return chain.filter(exchange);
            }
        }
        // 判断请求有没有携带token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if (StrUtil.isEmpty(token)){
            respons.setStatusCode(HttpStatus.UNAUTHORIZED);
            return respons.setComplete();
        }
        // 判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int code = AppJwtUtil.verifyToken(claimsBody);
            if (code == 1 || code == 2){
                // token过期
                respons.setStatusCode(HttpStatus.UNAUTHORIZED);
                return respons.setComplete();
            }
        } catch (Exception e) {
            // token校验失败
            respons.setStatusCode(HttpStatus.UNAUTHORIZED);
            return respons.setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
